﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Web.UI;
using CDSBDemandControl.Model;

namespace CDSBDemandControl.Configuration
{
    public static class CommonFunctions
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="Item"></param>
        /// <param name="Collection"></param>
        /// <returns></returns>
        public static bool CheckExistsWithin(this string Item, List<string> Collection)
        {
            return Collection.Contains(Item);
        }

        public static bool CheckExistsWithin(this string Item, IEnumerable<DeveloperModel> Collection)
        {
            bool ExistsWithin = false;

            foreach (DeveloperModel Developer in Collection)
            {
                if (Developer.DeveloperName == Item)
                {
                    ExistsWithin = true;
                    break;
                }
            }

            return ExistsWithin;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="mission"></param>
        /// <returns></returns>
        public static Mission GetMissionByName(this string mission)
        {
            Mission EnumMission = Mission.Developer;

            switch (mission)
            {
                case "Lider":
                    EnumMission = Mission.Leader;
                    break;
                case "Ponto Focal":
                    EnumMission = Mission.FocalPoint;
                    break;
                case "Desenvolvedor":
                    EnumMission = Mission.Developer;
                    break;
                default:
                    EnumMission = Mission.Outros;
                    break;
            }

            return EnumMission;
        }

        public static bool CheckExistsWithin(this DemandModel Item, List<DemandModel> Collection)
        {
            bool ExistsWithin = false;

            foreach (DemandModel Demand in Collection)
            {
                if (Demand.ID == Item.ID)
                {
                    ExistsWithin = true;
                    break;
                }
            }

            return ExistsWithin;
        }

        /// <summary>
        /// Retorna o Líder do desenvolvedor a partir da lista dos desenvolvedores
        /// </summary>
        /// <returns></returns>
        public static DeveloperModel GetDeveloperLeader(this DeveloperModel Developer, IEnumerable<DeveloperModel> Developers)
        {
            return (from Dev in Developers where Dev.DeveloperTeam == Developer.DeveloperTeam && Dev.Mission == Mission.Leader select Dev).First();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="developerName"></param>
        /// <param name="developers"></param>
        /// <returns></returns>
        public static string GetFactory(this string developerName, IEnumerable<DeveloperModel> developers)
        {
            string Factory = "";

            foreach (DeveloperModel developer in developers)
            {
                if (developer.DeveloperName == developerName)
                {
                    Factory = developer.DeveloperTeam.Contains("VCoding") ? developer.DeveloperTeam.Split('-')[0] : "CDSB";
                    break;
                }
            }

            if (Factory.Length == 0)
                throw new Exception("Factory Not Found");
            else
                return Factory;
        }

        /// <summary>
        /// Retorna um DateTime a partir de uma data informada no formato brasileiro
        /// </summary>
        /// <param name="date">String</param>
        /// <returns>DateTime</returns>
        public static DateTime? ToDateTimeForBrazilianDateFormat(this string date)
        {
            DateTime? dateTime;

            try
            {
                string[] dateArray = date.Split('/');
                dateTime = new DateTime(Convert.ToInt32(dateArray[2]), Convert.ToInt32(dateArray[1]), Convert.ToInt32(dateArray[0]));
            }
            catch
            {
                dateTime = null;
            }

            return dateTime;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        public static string ToBrazilianShortDateForUSAShortDate(this string date)
        {
            string ShortDate;

            try
            {
                string[] dateArray = date.Split(' ')[0].Split('-');
                ShortDate = string.Format("{0}/{1}/{2}", dateArray[2], dateArray[1], dateArray[0]);
            }
            catch
            {
                ShortDate = string.Empty;
            }

            return ShortDate;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="Developer"></param>
        /// <returns></returns>
        public static bool IsInFreeDaysPaid(this DeveloperModel Developer)
        {
            bool IsInFreeDays = false;

            if (Developer.StartFreeDaysPaid.HasValue && Developer.FinishFreeDaysPaid.HasValue)
            {
                IsInFreeDays = ((Developer.StartFreeDaysPaid.Value.Date <= DateTime.Now.Date) && (DateTime.Now.Date <= Developer.FinishFreeDaysPaid.Value.Date)) ? true : false;
            }

            return IsInFreeDays;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="collection"></param>
        /// <returns></returns>
        public static string ToInlineString(this List<string> collection)
        {
            string inLineString = " ";

            foreach (string item in collection)
            {
                inLineString += inLineString[inLineString.Length - 1] == '\'' ? ",'" + item + "'" : "'" + item + "'";
            }

            return inLineString.Trim();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="developers"></param>
        /// <returns></returns>
        public static string ToInlineString(this IEnumerable<DeveloperModel> developers)
        {
            string inLineString = " ";

            foreach (DeveloperModel developer in developers)
            {
                inLineString += inLineString[inLineString.Length - 1] == '\'' ? ",'" + developer.DeveloperName + "'" : "'" + developer.DeveloperName + "'";
            }

            return inLineString.Trim();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="NumberofdaysAfter"></param>
        /// <returns></returns>
        public static DateTime GetdaysAfter(this DateTime date, int NumberofdaysAfter)
        {
            int ValidDays = 1;
            DateTime DayAfter = date;

            while (ValidDays <= NumberofdaysAfter)
            {
                DayAfter = DayAfter.AddDays(1);

                if (DayAfter.DayOfWeek != DayOfWeek.Saturday && DayAfter.DayOfWeek != DayOfWeek.Sunday)
                {
                    ValidDays++;
                }
            }

            return DayAfter;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="Numberofdaysprior"></param>
        /// <returns></returns>
        public static DateTime GetdaysBefore(this DateTime date, int Numberofdaysprior)
        {
            int ValidDays = 1;
            DateTime DayBefore = date;

            while (ValidDays <= Numberofdaysprior)
            {
                DateTime Date = DateTime.Now.Subtract((new TimeSpan(3, 0, 0, 0)));

                if (Date.DayOfWeek != DayOfWeek.Saturday && Date.DayOfWeek != DayOfWeek.Sunday)
                {
                    ValidDays++;
                    DayBefore = Date;
                }
            }

            return DayBefore;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="developers"></param>
        /// <returns></returns>
        public static List<String> ToNameList(this IEnumerable<DeveloperModel> developers)
        {
            List<String> NameList = new List<string>();

            foreach (DeveloperModel developer in developers)
            {
                NameList.Add(developer.DeveloperName);
            }

            return NameList;
        }

        /// <summary>
        /// Retorna a média de dias em atraso de uma lista de tarefas.
        /// </summary>
        /// <param name="demandCollection">Lista de Demandas</param>
        /// <returns>double</returns>
        public static double GetAverageDelays(this IEnumerable<DemandModel> demandCollection)
        {
            int DaysPast = 0;

            foreach (DemandModel Demanda in demandCollection)
            {
                DaysPast += Demanda.DaysPast;
            }

            double Average = 0;

            if (DaysPast > 0)
                Average = (DaysPast / demandCollection.Count<DemandModel>());

            return Average;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="developerName"></param>
        /// <param name="?"></param>
        /// <returns></returns>
        public static DeveloperModel GetDeveloperByName(this IEnumerable<DeveloperModel> developerCollection, string developerName)
        {
            DeveloperModel DeveloperFound = null;

            if (developerCollection != null)
            {
                foreach (DeveloperModel Developer in developerCollection)
                {
                    if (developerName.Equals(Developer.DeveloperName) && Developer.Mission == Mission.Developer)
                    {
                        DeveloperFound = Developer;
                        break;
                    }
                }
            }
            return DeveloperFound;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="developerName"></param>
        /// <param name="?"></param>
        /// <returns></returns>
        public static DeveloperModel GetLeaderByTeam(this IEnumerable<DeveloperModel> developerCollection, string teamName)
        {
            DeveloperModel DeveloperFound = null;

            if (developerCollection != null)
            {
                foreach (DeveloperModel Developer in developerCollection)
                {
                    if (teamName.ToLower().Contains("7comm") || teamName.ToLower().Contains("vcoding"))
                        teamName = "CDSB-VCoding";

                    if (teamName.ToLower().Contains("suporte") || teamName.ToLower().Contains("3º") || teamName.ToLower().Contains("nível"))
                    {
                        teamName = "TimeA";
                    }

                    if (teamName.Equals(Developer.DeveloperTeam) && Developer.Mission == Mission.Leader)
                    {
                        DeveloperFound = Developer;
                        break;
                    }
                }
            }
            return DeveloperFound;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="developerName"></param>
        /// <param name="?"></param>
        /// <returns></returns>
        public static DeveloperModel GetFocalPointByProject(this IEnumerable<DeveloperModel> developerCollection, string projectName)
        {
            DeveloperModel DeveloperFound = null;

            if (developerCollection != null)
            {
                foreach (DeveloperModel Developer in developerCollection)
                {
                    if (Developer.ResponsibleFor.Count != 0 && Developer.ResponsibleFor.Contains(projectName) && Developer.Mission == Mission.FocalPoint)
                    {
                        DeveloperFound = Developer;
                        break;
                    }
                }
            }
            return DeveloperFound;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="developerName"></param>
        /// <param name="?"></param>
        /// <returns></returns>
        public static void ClearRanking(this IEnumerable<DeveloperModel> developerCollection)
        {
            if (developerCollection != null)
            {
                foreach (DeveloperModel Developer in developerCollection)
                {
                    Developer.TasksImplemented = 0;
                    Developer.TasksReleasedLate = 0;
                    Developer.TasksDisapprovedInCodeReview = 0;
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="inteiro"></param>
        /// <param name="inteiroCompare"></param>
        /// <returns></returns>
        public static int ReturMore(this int inteiro, int inteiroCompare)
        {
            if (inteiro > inteiroCompare)
                return inteiro;
            else
                return inteiroCompare;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="controlCollection"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static IEnumerable<Control> GetControlByType(this ControlCollection controlCollection, Type type)
        {
            IEnumerable<Control> Controls = from Controle in controlCollection.Cast<Control>() where Controle.GetType() == type select Controle;

            return Controls;
        }

        /// <summary>
        /// Retorna o número de dias úteis até a data final informada.
        /// </summary>
        /// <param name="startDate">DateTime</param>
        /// <param name="finishDate">DateTime</param>
        /// <returns>int</returns>
        public static int GetBusinessHoursUntil(this DateTime startDate, DateTime finishDate)
        {
            int Hours = 0;

            DateTime CheckDay = startDate;

            while (CheckDay <= finishDate)
            {
                if (CheckDay.DayOfWeek != DayOfWeek.Saturday && CheckDay.DayOfWeek != DayOfWeek.Sunday)
                {
                    Hours += 8;
                }

                CheckDay = CheckDay.AddDays(1);
            }

            return Hours;
        }

        public static bool CheckFilterFactory(this string valor, FiltroFabrica filtro)
        {
            bool Check = false;

            switch (filtro)
            {
                case FiltroFabrica.CDSB:
                    if (valor.ToLower() == "cdsb") Check = true;
                    break;
                case FiltroFabrica.SevenCOMm:
                    if (valor.ToLower() == "7comm") Check = true;
                    break;
                case FiltroFabrica.Todos:
                    if (valor.ToLower() == "cdsb" || valor.ToLower() == "7comm" || valor.ToLower() == "vcoding") Check = true;
                    break;
            }

            return Check;
        }

        public static bool CheckFilterProject(this string valor, FiltroProjeto filtro)
        {
            bool Check = false;

            switch (filtro)
            {
                case FiltroProjeto.Sinacor:
                    if (ConfigManager.GetTeamProjectsSinacor().Contains(valor)) Check = true;
                    break;
                case FiltroProjeto.iMercado:
                    if (ConfigManager.GetTeamProjectsIMercado().Contains(valor)) Check = true;
                    break;
                case FiltroProjeto.SiteBVMF:
                    if (ConfigManager.GetTeamProjectsSiteBVMF().Contains(valor)) Check = true;
                    break;
                case FiltroProjeto.Todos:

                    if (ConfigManager.GetTeamProjectsSinacor().Contains(valor)
                        || ConfigManager.GetTeamProjectsIMercado().Contains(valor)
                            || ConfigManager.GetTeamProjectsSiteBVMF().Contains(valor))
                        Check = true;
                    break;
            }

            return Check;
        }

        public static EnumGravity ToEnumGravity(this string value)
        {
            EnumGravity Gravity = EnumGravity.Unkown;

            switch (value)
            {
                case "Obstáculo":
                    Gravity = EnumGravity.Obstáculo;
                    break;
                case "Travamento":
                    Gravity = EnumGravity.Travamento;
                    break;
                case "Grande":
                    Gravity = EnumGravity.Grande;
                    break;
                case "Pequeno":
                    Gravity = EnumGravity.Pequeno;
                    break;
                case "Mínimo":
                    Gravity = EnumGravity.Minimo;
                    break;
                case "Recurso":
                    Gravity = EnumGravity.Recurso;
                    break;
                case "Texto":
                    Gravity = EnumGravity.Texto;
                    break;
                case "Trivial":
                    Gravity = EnumGravity.Trivial;
                    break;
            }

            return Gravity;
        }

        public static EnumPriority ToEnumPriority(this string value)
        {
            EnumPriority Priority = EnumPriority.Unkown;

            switch (value)
            {
                case "Urgente":
                    Priority = EnumPriority.Urgente;
                    break;
                case "Imediato:":
                    Priority = EnumPriority.Urgente;
                    break;
                case "Alta":
                    Priority = EnumPriority.Alta;
                    break;
                case "Normal":
                    Priority = EnumPriority.Normal;
                    break;
                case "Baixa":
                    Priority = EnumPriority.Baixa;
                    break;
            }

            return Priority;
        }

        public static EnumOrigin ToEnumOrigin(this string value)
        {
            EnumOrigin Origin = EnumOrigin.Unkown;

            switch (value)
            {
                case "Produção":
                    Origin = EnumOrigin.Producao;
                    break;
                case "Aceite":
                    Origin = EnumOrigin.Aceite;
                    break;
                case "Integra":
                    Origin = EnumOrigin.Integra;
                    break;
                case "Desenvolvimento":
                    Origin = EnumOrigin.Desenvolvimento;
                    break;
                case "Corretora":
                    Origin = EnumOrigin.Corretora;
                    break;
                case "Corretoras":
                    Origin = EnumOrigin.Corretoras;
                    break;
            }

            return Origin;
        }

        public static String ShortenName(this string value) 
        {
            string[] namesOfUser = value.Split(' ');
            
            int countSpace = (namesOfUser.Length - 1);

            for (int s = 0; s < namesOfUser.Length; s++)
            {
                namesOfUser[s] = namesOfUser[s] + " ";

                if (s != 0 && s != namesOfUser.Length - 1)
                {
                    if (namesOfUser[s].ToLower().Trim().Length > 3)
                        namesOfUser[s] = namesOfUser[s].Substring(0, 1) + ". ";
                }
            }

            return String.Concat(namesOfUser);
        }
    }
}
